<?php
defined('APP_PATH') or die ('Unauthorized access'); 
/**
 * Db类
 * @author windpurple
 * @version 1.0
 */
require_once(LIB_PATH.'/Interface/DbInterface.php');
class Db implements Db_Interface
{
	static private $link = NULL ;
	private $_database;
	private $_table;
	private $_sql;
	const RESULT_TYPE = MYSQL_ASSOC;
	static private $_instance = NULL;
	
	/**
	 * 私有化构造函数
	 */
	private function __construct()
	{
		$this->Connect();
		if(!is_resource(self::$link)) Error::message('数据库连接失败！请检查配置');
	}
	
	/**
	 * 私有化克隆对象
	 */
	private function __clone()
	{
		
	}
	
	
	/**
	 * 单一访问统一入口
	 * @return object
	 */
	static public function getInstance()
	{
		if(is_null(self::$_instance) || !isset(self::$_instance)){
			self::$_instance = new Db();
		}
		return self::$_instance;
	}
	
	/**
	 * 连接数据库
	 */
	private function Connect()
	{
		
		global $config;
		!isset($config['database']) ? Error::message('未定义数据库配置') : '';
		if(is_null(self::$link) || !isset(self::$link)){
			self::$link = mysql_connect(
								$config['database']['db_host'].':'.$config['database']['db_port'],
								$config['database']['db_user'],
								$config['database']['db_pass']) 
								or
								Error::message(mysql_error());
		}
		return self::$link;
	}
	
	/**
	 * 选择数据库
	 * @param $arr
	 */
	public function Config($arr)
	{
		global $config;
		$this->_database = !isset($arr['database']) ? $config['database']['db_default'] : $arr['database'];
		$select = mysql_select_db($this->_database,self::$link) or Error::message(mysql_error());
		$this->query("SET NAMES ".$config['database']['db_charset']);
		//验证表是否存在
		$check_table = mysql_fetch_array($this->query("show tables like '{$arr['table']}'"));
		if(empty($check_table)) Error::message("数据库 {$this->_database} 中表 {$arr['table']} 不存在！");
		$this->_table = $arr['table'];
		return $select;
	}
	
	/**
	 * query
	 * @param unknown_type $sql
	 */
	private function query($sql,$param = false)
	{
		$this->_sql = '';
		if(!$param){
			return mysql_query($sql);
		}
	}
	
	/**
	 * select
	 * @param unknown_type $select
	 */
	private function select($select)
	{
		if(is_array($select)){
			return implode(' , ',$select);
		}else{
			return "*";
		}
		
	}
	
	/**
	 * 
	 * @param unknown_type $condition = array(array('a','<','b'))
	 */
	private function where($condition)
	{
		if(empty($condition)){
			return '';
		}
		
		if(!is_array($condition[0])){
			$condition[1] = strtoupper($condition[1]);
			if($condition[1] != 'IN'){
				$where = $condition[0].' '.$condition[1]." '".$condition[2]."'";
			}else{
				$where = $condition[0].' '.$condition[1].' '.$condition[2];
			}
		}elseif(count($condition) == 1){
			$condition[0][1] = strtoupper($condition[0][1]);
			if($condition[0][1] != 'IN'){
				$where = $condition[0][0].' '.$condition[0][1]." '".$condition[0][2]."'";
			}else{
				$where = $condition[0][0].' '.$condition[0][1].' '.$condition[0][2];
			}
		}else{
			$where = '';
			foreach($condition as $k => $v){
				$v[1] = strtoupper($v[1]);
				if($v[1] != 'IN'){
					$where .= $v[0].$v[1]."'".$v[2]."' AND ";
				}else{
					$where .= $v[0].' '.$v[1].' '.$v[2].' AND ';
				}
			}
			$where = substr($where,0,-5);
		}
		return " WHERE $where";
	}
	
	/**
	 * limit
	 * @param unknown_type $page
	 * @param unknown_type $size
	 */
	public function limit($page,$size = '')
	{
		if(empty($size)){
			$this->_sql .= ' LIMIT '.$page;
		}else{
			$this->_sql .= " LIMIT $page , $size";
		}
	}
	
	/**
	 * group
	 * @param unknown_type $group
	 */
	public function group($group)
	{
		$this->_sql .= " GROUP BY $group";
		$this->_sql = preg_replace("/GROUP BY (.*)C+(.*)/is"," GROUP BY $group$2 ",$this->_sql);
		
	}
	
	public function order($order)
	{
		$this->_sql .= " ORDER BY $order";
		$this->_sql = preg_replace("/ORDER BY (.*)C+(.*)/is"," ORDER BY $order$2 ",$this->_sql);
	}
	
	/**
	 * 
	 */
	public function nums($condition = '',$select = '',$sql = '')
	{
		if(empty($sql)){
			$condition = $this->where($condition);
			$select = $this->select($select);
			$sql = "SELECT {$select} FROM `{$this->_table}` ".$condition.$this->_sql;
		}
		$query = $this->query($sql);
		return mysql_num_rows($query);
	}
	
	/**
	 * 查询一条记录
	 * @param unknown_type $condition
	 * @param unknown_type $select
	 */
	public function find($condition,$select = '',$sql = '')
	{
		if(empty($sql)){
			$condition = $this->where($condition);
			$select = $this->select($select);
			$sql = "SELECT {$select} FROM `{$this->_table}` ".$condition.$this->_sql;
		}
		//echo $sql;exit;
		$query = $this->query($sql);
		return mysql_fetch_array($query,self::RESULT_TYPE);
	}
	
	/**
	 * 查询所有记录
	 * @param unknown_type $condition
	 * @param unknown_type $select
	 */
	public function fetchAll($condition = '',$select = '',$sql = '')
	{
		$result = array();
		
		if(empty($sql)){
			$condition = $this->where($condition);
			$select = $this->select($select);
			$sql = "SELECT {$select} FROM `{$this->_table}` ".$condition.$this->_sql;
		}
		//echo $sql;
		$query = $this->query($sql);
		while($row = mysql_fetch_array($query,self::RESULT_TYPE)){
			$result[] = $row;
		}
		return $result;
	}
	

	
	/**
	 * 更新
	 * @param unknown_type $data
	 * @param unknown_type $condition
	 */
	public function update($data,$condition = array(),$sql = '')
	{
		if(empty($sql)){
			$set = '';
			foreach($data as $k => $v){
				if(strpos($v,$k) === 0 && (count(explode('+',$v)) > 1 || count(explode('-',$v)) > 1)){
					$set .= $k.' = '.$v.',';
				}else{
					$set .= $k." = '".$v."',";
				}
			}
			$set = substr($set,0,-1);
			$condition = empty($condition) ? 1 : $this->where($condition);
			$sql = "UPDATE `{$this->_table}` SET ".$set." {$condition}";
		}
		return $this->query($sql);
	}
	
	/**
	 * 插入
	 * @param unknown_type $data
	 */
	public function insert($data = array(),$sql = '')
	{
		if(empty($sql)){
			$key = array_keys($data);
			$value = array_values($data);
			$sql = "INSERT INTO `{$this->_table}` (".implode(',',$key).") VALUES ('".implode("','",$value)."')";
		}
		$this->query($sql);
		$last = $this->query("SELECT LAST_INSERT_ID()");
		$last = mysql_fetch_array($last);
		return $last[0];
		//return mysql_insert_id();
	}
	
	/**
	 * 删除
	 * @param unknown_type $where = array(array('a','b','<'))
	 */
	public function delete($condition = array(),$sql = '')
	{
		if(empty($sql)){
			$condition = empty($condition) ? 1 : $this->where($condition);
			$sql = "DELETE FROM `{$this->_table}` {$condition}";
		}
		return $this->query($sql);
		
	}
	
	public function close()
	{
		return mysql_close();
	}
	

	
}


?>